package com.wuhao.shootclient.base

import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.coder.vincent.smart_dialog.SmartDialog
import com.coder.vincent.smart_dialog.loading.BoxSize
import com.coder.vincent.smart_dialog.loading.LoadingDialogFacade
import com.drake.statusbar.immersive

abstract class EngineActivity<B : ViewDataBinding>(@LayoutRes contentLayoutId: Int = 0) :
    AppCompatActivity(contentLayoutId), OnClickListener {


    lateinit var binding: B
    lateinit var rootView: View
    private var onTouchEvent: (MotionEvent.() -> Boolean)? = null


    override fun setContentView(layoutResId: Int) {
        rootView = layoutInflater.inflate(layoutResId, null)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)//常亮
        setContentView(rootView)

        immersive(rootView.rootView, true)

        binding = DataBindingUtil.bind(rootView)!!
        init()
    }

    open fun init() {
//        try {
            initView()
            initData()
//        } catch (e: Exception) {
//            Log.e("Engine", "Initializing failure", e)
//        }
    }

    protected abstract fun initView()
    protected abstract fun initData()
    override fun onClick(v: View) {}

    /**
     * 触摸事件
     * @param block 返回值表示是否拦截事件
     */
    fun onTouchEvent(block: MotionEvent.() -> Boolean) {
        onTouchEvent = block
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        val b = super.dispatchTouchEvent(event)
        return onTouchEvent?.invoke(event) ?: b
    }

    fun requireActivity(): AppCompatActivity {
        return this
    }
    private var loadingDialog: LoadingDialogFacade.Handle? = null
    fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = SmartDialog.builderOfLoading()
                .message("正在加载")
                .boxSize(BoxSize.MIDDLE)
                .build(this)
        }
        loadingDialog?.show()
    }

    fun dismissLoading() {
        loadingDialog?.dismiss()
    }

    /**
     * 关闭界面
     */
    fun finishTransition() {
        finishAfterTransition()
    }
}